﻿using Architecture.Service.Impl;
using Architecture.Service.Interface;
using Architecture.Service;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Architecture.Repository.Interface;
using Architecture.Repository.Impl;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using Architecture.Service.Rabbit;
using Architecture.Repository.InterfaceRabbit;
using Architecture.Repository.ImplRabbit;
using Architecture.Repository;
using Architecture.Domain;

namespace Architecture.Api.Extensions
{
    public static class SericeCollectionExtensions
    {
        /// <summary>
        /// this 拓展语法
        /// string 代表 被扩展的类型
        /// </summary>
        /// <param name="para">扩展方法传入的值</param>
        /// <returns></returns>
        public static int ToInt(this string para)
        {
            int result = 0;
            if(int.TryParse(para.Substring(6,8), out result))
            {
                return result;
            }
            else
            {
                return -1111;
            }
        }
        /// <summary>
        /// 截取身份证号
        /// </summary>
        /// <param name="idCard"></param>
        /// <returns></returns>
        public static string GetBirthDay(this string idCard)
        {
            return idCard.Substring(6,8);
        }
        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="Servicess"></param>
        /// <returns></returns>
        public static IServiceCollection AddService(this IServiceCollection Servicess)
        {
            #region RBAC
            //用户
            Servicess.AddScoped<IUserService, UserService>();
            Servicess.AddScoped<IUserRepository, UserRepository>();
            Servicess.AddScoped<IProvinceRepository, ProvinceRepository>();
            Servicess.AddScoped<IUrbanRepository, UrbanRepository>();
            Servicess.AddScoped<ICountyRepository, CountyRepository>();
            //角色
            Servicess.AddScoped<IRoleService, RoleService>();
            Servicess.AddScoped<IRoleRepository, RoleRepository>();
            //用户角色关联表
            Servicess.AddScoped<IRelatedRepository, RelatedRepository>();
            //菜单
            Servicess.AddScoped<IMenuService, MenuService>();
            Servicess.AddScoped<IMenuRepository, MenuRepository>();
            //菜单角色关联表
            Servicess.AddScoped<IPrivilegRepository, PrivilegRepository>();
            //请假
            Servicess.AddScoped<ILeaveService, LeaveService>();
            Servicess.AddScoped<ILeaveRepository, LeaveRepository>();
            #endregion
            //溯源
            Servicess.AddScoped<ITraceService, TraceService>();
            Servicess.AddScoped<ITraceabilityRepository,TraceabilityRepository>();
            //商品名称
            Servicess.AddScoped<IRepository<Goods>,BaseRepository<Goods>> ();
            //养殖
            Servicess.AddScoped<IFarmingRepository, FarmingRepository>();
            //保健
            Servicess.AddScoped<IHealthRepository, HealthRepository>();
            //企业
            Servicess.AddScoped<IBusinessRepository, BusinessRepository>();
            //图片
            Servicess.AddScoped<IPhotoRepositroy, PhotoRepository>();
            //屠宰
            Servicess.AddScoped<ISlaughterRepository, SlaughterRepository>();
            //深加工
            Servicess.AddScoped<IProcessingRepository, ProcessingRepository>();
            return Servicess;
        }
        /// <summary>
        /// 注册数据库
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="Servicess"></param>
        /// <param name="ConnectionString"></param>
        /// <param name="enableSqlLog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDBcontextService<TDbContext>(this IServiceCollection Servicess,string? ConnectionString, bool enableSqlLog)where TDbContext:DbContext
        {
            return Servicess.AddDbContext<TDbContext>(builder =>
            {
                builder.UseSqlServer(ConnectionString, action =>
                {
                    action.EnableRetryOnFailure(
                        maxRetryCount:10,
                        maxRetryDelay:TimeSpan.FromSeconds(60),//时间/秒
                        errorNumbersToAdd:null);
                }).EnableSensitiveDataLogging();
                if (enableSqlLog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }

        public static void AddJWT(this IServiceCollection collection,WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(oprions =>
            {
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                oprions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    // 验证是否过期
                    ValidateLifetime = true,
                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                };
            });
        }
    }
}
